// pages/xxx.js
//引入插件
const plugin = requirePlugin("WechatSI");
const mybehavior = require("../../../../../behaviors/requests")
//创建InnerAudioContext音频对象。
const innerAudioContext = wx.createInnerAudioContext();
Page({

  /**
   * 页面的初始数据
   */
  behaviors: [mybehavior],
  data: {
    baseUrl: "https://logisticsengineering.gree.com/map_api",
    location: {
      latitude: 0,
      longitude: 0
    },
    markers: [
      {
        id: 1,
        latitude: 22.23155,
        longitude: 113.49429,
        callout: {
          color:'#000',
          content:'九期B座',
          fontSize:16,
          borderRadius:5,
          bgColor:'#ffffff',
          padding:8,
          textAlign:'center',
          display:'ALWAYS'

        },
      },

    ],
    polyline: [],
    distance: "",
    navigation: "",

    circles: [  
      {
        latitude: 22.23422,
        longitude: 113.49442,
        radius: 10,
        fillColor: "#7cb5ec88",
        color: '#FF0000DD',
      },
      {
        latitude: 22.23144,
        longitude: 113.49448,
        radius: 10,
        fillColor: "#7cb5ec88",
        color: '#FF0000DD',
      },
    ],
    map_points: [
      {
        latitude: 22.23422,
        longitude: 113.49442,
        tips: "当前路段直行约250，前方路口右转！",
        index: 0,
      },
      {
        index: 1,
        latitude: 22.23192,
        longitude: 113.49481,
        tips: "当前路口右转，然后直行约40米！"
      },
      {
        index: 2,
        latitude: 22.23186,
        longitude: 113.49443,
        tips: "当前路口左转，直行约50米，然后到达目的地附近！"
      },
      {
        index: 3,
        latitude: 22.23144,
        longitude: 113.49448,
        tips: "到达目的地附近！"
      },

    ],
    line_Choose_Show: false,
    line_add_Show: false,
    start_columns: ["8号门", "2号门"],
    end_columns: ["九期B座", "食堂"],
    map_start: "",
    map_end: "",
    map_list: [

    ],
    map_list_show: false,
    line_list: [],
    map_points: [],
    map_scale: 16,
    start_btn_show: false,
  },
  markerTap(e) {
    console.log(e);
    let marker_arr = this.data.markers
  },
  // 添加一行地图坐标数据
  addMapData() {
    let lists = this.data.map_list
    let obj = {
      index:lists.length,
      latitude: "",
      longitude: "",
      tips: ""
    }
    lists.push(obj)
    this.setData({
      map_list: lists,
    })
  },
  // 双向绑定地图坐标数据
  bindMapData(e) {
    let id_ = e.target.dataset.id
    let index = e.target.dataset.index
    let lists = this.data.map_list
    lists[index][id_] = e.detail
    this.setData({
      map_list: lists
    })
  },
  // 删除一行地图坐标数据
  deleteMapData(e) {
    console.log(e);
    console.log(this.data.map_list);
    let index = e.target.dataset.index
    let lists = this.data.map_list
    lists.splice(index, 1)
    for (let i = 0; i < lists.length; i++) {
      lists[i].index = i
    }
    this.setData({
      map_list: lists,
    })
  },
  // 下拉选择
  getPickerVlaue(e) {
    let key = e.target.id
    this.setData({
      [key]: e.detail
    })

  },
  // 添加路线表单弹出
  addLineShow() {
    this.setData({
      line_add_Show: true,

    })
  },
  // 关闭添加路线表单
  onCloseAdd() {
    this.setData({
      line_add_Show: false,
      map_list: [
     
      ],
      map_end: "",
      map_start: "",
    })
  },
  // 重置添加路线表单
  resetMapList() {
    this.setData({
      map_list: [
      ],
      map_end: "",
      map_start: "",
    })
  },

  // 添加路线
  addLine() {
    let url = this.data.baseUrl + "/new_line";
    let data = {
      point: this.data.map_list,
      map_start: this.data.map_start,
      map_end: this.data.map_end,
    }
    this.post(url, data).then(res => {
      console.log("返回结果", res)
      if (res.code == 20000) {
        wx.showToast({
          title: res.msg,
          icon: "success"
        });
        this.onCloseAdd()
        this.getLineData()
      } else {
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })


  },

  // 删除路线
  deleteLineData(e) {
    wx.showModal({
      title: '确定删除改路线？',
      content: '',
      complete: (res) => {
        if (res.cancel) {
          wx.showToast({
            title: '已取消！',
            icon: 'none'
          })
        }
        if (res.confirm) {
          let key = e.currentTarget.dataset.row._id
          let url = this.data.baseUrl + "/delete_line";
          let data = {
            key: key,
          }
          this.post(url, data).then(res => {
            console.log("返回结果", res)
            if (res.code == 20000) {
              wx.showToast({
                title: res.msg,
                icon: "success"
              });
              this.getLineData()
            } else {
              wx.showToast({
                title: res.msg,
                icon: "error"
              })
            }
          }).catch(err => {
            wx.showToast({
              title: err.msg,
              icon: 'error'
            })
          })
        }
      }
    })

  },

  // 路线选择弹窗显示
  lineChooseShow() {
    this.setData({
      line_Choose_Show: true
    })
  },

  // 路线确定渲染
  lineChoose(e) {
    this.setData({
      line_Choose_Show: false
    })
    this.startLocationUpdate();

    const points = e.currentTarget.dataset.row.point
    let index = 0;
    let timer = setInterval(() => {
      if (index < points.length) {
        let marker = [{
          id: 1,
          longitude: points[index].longitude,
          latitude: points[index].latitude,
          iconPath: 'https://logisticsengineering.gree.com/container_manage_api/container_manage/fs_download?file_id=10d54868434411ef8c0d005056af36f8',
          width: 30,
          height: 30
        }];
        let polyline = [{
          points: points.slice(0, index + 1),
          color: "#FF0000DD",
          width: 2,
          dottedLine: false
        }];

        this.setData({
          longitude: points[index].longitude,
          latitude: points[index].latitude,
          markers: marker,
          polyline: polyline
        })
        index++;
      } else {
        clearInterval(timer);
      }
    }, 1000)

  },
  // 查询-路线--集合
  getLineData() {
    let url = this.data.baseUrl + "/get_line";
    let data = {
    }

    this.post(url, data).then(res => {
      console.log("返回结果", res)
      if (res.code == 20000) {
        this.setData({
          line_list: res.data.table_data
        })
        // wx.showToast({
        //   title: res.msg,
        //   icon: "success"
        // });
      } else {
        this.setData({
          line_list: []
        })
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {
      this.setData({
        line_list: []
      })
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },

  // 刷新用户当前位置
  startLocationUpdate() {
    this.updateLocation();
    this.interval = setInterval(() => {
      this.updateLocation();
    }, 2000); // 每隔2秒更新一次位置
  },
  // 获取当前位置
  updateLocation() {
 
    for (let i = 0; i < this.data.map_points.length; i++) {
      const distance = this.getDistance(this.data.location.latitude, this.data.location.longitude, this.data.map_points[i].latitude, this.data.map_points[i].longitude)
      console.log(distance);
      if (distance < 20) {
        // wx.showToast({
        //     title: this.data.map_points[i].tips,
        // })
        this.setData({
          navigation: this.data.map_points[i].tips
        })
        this.handleStart()
      }
    }
  },
  // 定位到当前位置
  moveToLocation() {
    const mapContext = wx.createMapContext('map');
    mapContext.moveToLocation({
      latitude: this.data.location.latitude,
      longitude: this.data.location.longitude
    });
  },
  // 停止刷新位置
  stopLocationUpdate() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  },
  test() {
    this.getDistance(22.23186, 113.49443, 22.23144, 113.49448)

  },
  // 计算两点距离
  getDistance(lat1, lon1, lat2, lon2) {
    const earthRadius = 6371;  // 地球半径，单位为千米
    const radLat1 = this.toRadians(lat1);
    const radLat2 = this.toRadians(lat2);
    const deltaLat = radLat2 - radLat1;
    const deltaLon = this.toRadians(lon2) - this.toRadians(lon1);

    const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
      Math.cos(radLat1) * Math.cos(radLat2) *
      Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = Math.floor(earthRadius * c * 1000);
    console.log("距离", distance);
    this.setData({
      distance: distance
    })

    return distance;
  },

  toRadians(degrees) {
    return degrees * Math.PI / 180;

  },

  //文字转语音
  handleStart() {
    plugin.textToSpeech({
      lang: "zh_CN",
      tts: true,
      content: this.data.navigation,
      success: (res) => {
        this.setData({
          src: res.filename,
        });
        this.audioPlay();
      },
      fail: (res) => {
        console.log("fail", res);
      },
    });
  },

  //结束语音
  handleEnd(e) {
    innerAudioContext.pause();
  },

  //播放语音
  audioPlay(e) {
    if (this.data.src == "") {
      console.log(`暂无语音`);
      return;
    }
    console.log("正在播放");
    innerAudioContext.autoplay = true;
    //设置音频地址
    innerAudioContext.src = this.data.src;
    //播放音频
    innerAudioContext.play();
  },
  // 开始导航
  startBtn() {
    if (this.data.polyline.length == 0) {
      wx.showModal({
        title: '请先选择路线！！',
        confirmText: "选择路线",
        complete: (res) => {
          if (res.cancel) {

          }

          if (res.confirm) {
            this.setData({
              line_Choose_Show: true,
            })

          }
        }
      })
    } else {
      this.setData({
        map_scale: 20,
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    this.updateLocation()
    this.getLineData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成                                                                         
   */
  onReady() {
    innerAudioContext.onError(function (res) {
      console.log("onError", res);
      wx.showToast({
        title: "播放失败",
        icon: "none",
      });
    });
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
4   */
  onUnload() {
    this.stopLocationUpdate();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})